<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { menuFormSchema } from './menu.data';
  import { getMenu, addMenu, updateMenu, getMenuListSimple } from '/@/api/project/menu';
  import { useUserStore } from '/@/store/modules/user';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'AddOrUpdateMenu',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const dataId = ref('');
      const userStore = useUserStore();
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      let currentProjectCode = userStore.getUserCurrentProjectCode;
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: menuFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        qcUnifyProps.value = unref(data);
        console.log('接收的对象', data.dataId);
        dataId.value = data.dataId;
        operateType.value = data.operateType;
        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });
        //加载新增/修改中父级部门下拉列表
        getMenus();
        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (data.operateType == OperationTypeEnum.EDIT) {
          getMenuById();
        }
      });

      /**
       * 根据菜单id获取菜单详细信息，用于编辑回显
       */
      async function getMenuById() {
        let flagOptions = [];
        flagOptions.push({ label: '启用', value: '0' }, { label: '禁用', value: '5' });
        getMenu(dataId.value)
          .then((res) => {
            console.log('res', res);
            setFieldsValue({
              ...res,
              parentid: res.parentid === 0 ? null : res.parentid,
            });
            updateSchema({
              field: 'flag',
              componentProps: {
                options: flagOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            const values = await validate();
            setModalProps({ confirmLoading: true });
            //调用接口进行保存
            addMenu(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          updateMenu(values)
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      /**
       * 获取菜单列表，新增/修改时父级菜单下拉列表
       */
      function getMenus() {
        //父级菜单选项集合
        let menuOptions = [];
        getMenuListSimple({ project: currentProjectCode, keywords: '' })
          .then((res) => {
            console.log('res', res);
            res.forEach((menu) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              let menuId: number = menu.id as number;
              //根据层级在菜单名称前添加空格，实测空格无效，显示时没有空格
              let prefixSpaces = '';
              //修改中父级菜单不选自己及下级菜单
              if (operateType.value == OperationTypeEnum.EDIT) {
                if (dataId.value != menu.id) {
                  if (dataId.value != menu.parentid) {
                    for (let index = 1; index < menu.level; index++) {
                      prefixSpaces += '----';
                    }
                    menuOptions.push({ value: menuId, label: prefixSpaces + menu.name });
                  }
                }
              } else {
                for (let index = 1; index < menu.level; index++) {
                  prefixSpaces += '----';
                }
                menuOptions.push({ value: menuId, label: prefixSpaces + menu.name });
              }
            });
            //设置父级菜单下拉列表
            updateSchema({
              field: 'parentid',
              componentProps: {
                options: menuOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      return {
        operateType,
        registerModal,
        registerForm,
        displayModuleTitle,
        onButtonOkClick,
        getMenuById,
        getMenus,
        opSuccess,
      };
    },
  });
</script>
